#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
PROG=/usr/bin/xunlei

get_config() {
	config_get_bool enabled $1 enabled 0
	config_get host $1 host "0.0.0.0"
	config_get port $1 port 5051
	config_get config_path $1 config_path "/etc/xunlei"
	config_get download_path $1 download_path "/tmp/downloads"
}

start_service() {
	config_load xunlei
	config_foreach get_config xunlei
	[ $enabled -ne 1 ] && return 1

	if [ ! -d "/usr/share/xunlei/target/var" ];then
		id=$(cat /proc/sys/kernel/random/uuid | cut -c1-7)
		echo "unique=\"synology_${id}_720+\"" > /usr/share/xunlei/target/host/etc/synoinfo.conf
	fi

	if [ -f /etc/synoinfo.conf ];then
		rm /etc/synoinfo.conf
	fi

	if [ -f /usr/syno/synoman/webman/modules/authenticate.cgi ];then
		rm /usr/syno/synoman/webman/modules/authenticate.cgi
	fi

	rm -rf /var/packages/pan-xunlei-com
	ln -s /usr/share/xunlei /var/packages/pan-xunlei-com
	ln -s /usr/share/xunlei/target/host/etc/synoinfo.conf /etc/synoinfo.conf
	ln -s /usr/share/xunlei/target/host/usr/syno/synoman/webman/modules/authenticate.cgi /usr/syno/synoman/webman/modules/authenticate.cgi
	args="--host $host --port $port --config-path $config_path --download-path $download_path"
	procd_open_instance
	procd_set_param command $PROG launch $args
	procd_set_param stdout 0
	procd_set_param stderr 0
	procd_set_param pidfile /var/run/xunlei.pid
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "xunlei"
}

reload_service() {
	stop
    for i in $(seq 1 20); do
        if [ -z "$(ps -ef | grep xunlei | grep -v grep | grep -v $$ |grep -v '/etc/rc.common' | grep -v '/sbin/service' | grep -v '/sbin/luci-reload')" ]; then
			break
        fi
        sleep 1
	done
	start
}
